﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing.Printing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using 多协议通信平台.Base;
using 多协议通信平台.Models;
using 多协议通信平台.Msg;

namespace 多协议通信平台.ViewModels.Protocal
{
    public partial class FinsViewModel : BaseViewModel
    {
        public FinsViewModel()
        {
            PageTitle = "FINS";
            WeakReferenceMessenger.Default.Register<NotifyMessage>(this, Receive);
            InitData();
        }

        private bool _isLoading;

        [ObservableProperty]
        private int slaveId;

        [ObservableProperty]
        private string portName;

        [ObservableProperty]
        private int baudRate = 9600;

        [ObservableProperty]
        private int dataBit = 8;

        [ObservableProperty]
        private Parity parity = Parity.None;

        [ObservableProperty]
        private StopBits stopBit = StopBits.One;

        [ObservableProperty]
        private string connectionStatus = "未连接";

        [ObservableProperty]
        private int interval = 1000;

        [ObservableProperty]
        private string primaryAddress;

        [ObservableProperty]
        private DataPoint selectedPoint;

        public ObservableCollection<FinsDataPoint> PointList { get; set; } = new ObservableCollection<FinsDataPoint>();

        private void InitData()
        {
            FinsDataPoint point1 = new FinsDataPoint() { StartAddr = "W0" };
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W1", PointValue = "0001" });
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W2", PointValue = "0002" });
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W3", PointValue = "0003" });
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W4", PointValue = "0004" });
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W5", PointValue = "0005" });
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W6", PointValue = "0006" });
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W7", PointValue = "0007" });
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W8", PointValue = "0008" });
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W9", PointValue = "0009" });
            point1.DataPoints.Add(new DataPoint() { PointAddress = "W10", PointValue = "0010" });

            PointList.Add(point1);
            for (int i = 1; i < 14; i++)
            {
                FinsDataPoint point = new FinsDataPoint() { StartAddr = $"W{i}0" };
                for (int j = 0; j < 10; j++)
                    point.DataPoints.Add(new DataPoint() { PointAddress = $"W{(i * 10 + j)}", PointValue = "0000" });
                PointList.Add(point);
            }

        }

        [RelayCommand]
        private void ConnectSerialPort()
        {

        }

        [RelayCommand]
        private void DisConnectSerialPort()
        {

        }

        private void LoadData()
        {
            FinsDataPoint? point = PointList.LastOrDefault();
            int startAddr = 13;
            for (int i = 1; i < 14; i++)
            {
                // startAddr
                FinsDataPoint point2 = new FinsDataPoint() { StartAddr = $"W{(startAddr + i)}0" };

                for (int j = 0; j < 10; j++)
                    point2.DataPoints.Add(new DataPoint() { PointAddress = $"W{((startAddr + i) * 10 + j)}", PointValue = "0000" });
                PointList.Add(point2);
            }
        }

        [RelayCommand]
        private void ShowEditDialog(UserControl control)
        {
            control.Visibility = Visibility.Visible;
        }

        [RelayCommand]
        private void SelectedCellsChanged(object obj)
        {
            DataGrid? dataGrid = obj as DataGrid;
            if (dataGrid == null) return;

            DataGridColumn column = dataGrid.SelectedCells[0].Column;
            int colIdx = dataGrid.Columns.IndexOf(column) - 1;
            if (colIdx == -1) return;

            if (dataGrid.SelectedCells.Count > 0 && dataGrid.SelectedCells[0].Item is FinsDataPoint finsDataPoint)
            {
                SelectedPoint = finsDataPoint.DataPoints[colIdx];
            }
            //if (e.AddedCells.Count > 0)
            //{
            //    string address = (string)e.AddedCells[0].Item; // 记录当前选中的单元格
            //    string startAddr = string.Concat(address.Substring(address.Length - 1),'0');
            //    SelectedPoint = PointList.FirstOrDefault(p => p.StartAddr == startAddr)?.DataPoints.FirstOrDefault(p => p.PointAddress == address);
            //}
            //else
            //{
            //    SelectedPoint = null;
            //}
        }

        private void Receive(object recipient, NotifyMessage message)
        {
            if ("load".Equals(message.MsgType))
            {
                LoadData();
            }
            else if ("Edit".Equals(message.MsgType))
            {
                if (message.Value is DataPoint point)
                {
                    // 处理编辑逻辑
                    Debug.WriteLine($"编辑点: {point.PointAddress}, 值: {point.PointValue}");
                    // 这里可以添加保存逻辑

                }
            }
        }
    }
}
